﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text.RegularExpressions;

namespace SemanticEx
{
	public class GenericParameterScope : IParameterScope
	{
		#region Constructors

		public GenericParameterScope()
		{
			Parameters = new List<ParameterExpression>();
		}

		#endregion

		#region Properties

		public IEnumerable<ParameterExpression> Parameters { get; protected set; }

		#endregion

		#region Methods

		public ParameterExpression FindSymbol(string name, Type type = null)
		{
			return Parameters.Where(x => x.Name == name).SingleOrDefault() ?? CreateSymbol(name, type);
		}

		protected ParameterExpression CreateSymbol(string name, Type type = null)
		{
			var newParam = Expression.Parameter(type ?? typeof(object), name);
			Parameters = Parameters.Concat(new[] { newParam });
			return newParam;
		}

		protected bool IsSymbolNameValid(string name)
		{
			return Regex.Match(name, @"^[_A-Za-z][_\w]*$").Success;
		}

		#endregion
	}
}